<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue';

import { StorageManager } from '@vben-core/shared/cache';

import MapboxLanguage from '@mapbox/mapbox-gl-language';
import {
  ElCol,
  ElDescriptions,
  ElDescriptionsItem,
  ElDialog,
  ElDivider,
  ElRow,
  ElScrollbar,
} from 'element-plus';
import mapboxgl from 'mapbox-gl';

import { rasterServiceApi } from '#/api';

import 'element-plus/theme-chalk/el-loading.css';

const props = defineProps({
  currentRasterData: {
    default: () => ({}),
    type: Object,
  },
  isDialogShow: {
    default: false,
    type: Boolean,
  },
  dataName: {
    default: 'No data has been selected!',
    type: String,
  },
});

const emits = defineEmits(['closePreviewDialog', 'deleteGeoData']);

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});

mapboxgl.accessToken =
  'pk.eyJ1IjoibmluamFhIiwiYSI6ImNsYXYzd3JwaDAyMGwzdm44ZmI3M212eHQifQ.h_dGMMOvQXNfmheNd0_j8A';
type PreviewData = {
  bbox: Array<number>;
  fileId: string;
  id: string;
  name: string;
  oriFileId: string;
  ownerCount: string;
  publisher: string;
  publishTime: string;
  type: string;
  url: string;
};

const { isDialogShow, currentRasterData } = toRefs(props);

const scene = reactive({
  map: null as any,
});
const publisher = storageManager.getItem('username');
const typeOfRaster = ref('other image');
const userId = storageManager.getItem('userId');
const preview = reactive({
  data: {} as PreviewData,
});
const isloading = ref(true);
const bboxTop = ref();
const bboxBottom = ref();
const bboxLeft = ref();
const bboxRight = ref();
const bandCount = ref(1);
const getBandCount = () => {
  rasterServiceApi
    .getBandCount(userId as string, preview.data.id)
    .then((response) => {
      bandCount.value = response;
    });
};
// const getBandCount = () => {
//   rasterServiceApi
//     .getBandCount(userId as string, preview.data.id)
//     .then((response) => {
//       if (response) {
//         bandCount.value = response;
//       }
//     });
// };

// 初始化地图
const initMap = () => {
  return new Promise((resolve) => {
    scene.map = new mapboxgl.Map({
      container: 'map', // container ID
      style: 'mapbox://styles/mapbox/streets-v11', // style URL
      center: [116.4, 39.9], // starting position [lng, lat]
      zoom: 8, // starting zoom
    });
    scene.map.addControl(
      new MapboxLanguage({
        defaultLanguage: 'zh-Hans',
      }),
    );
    scene.map.addControl(
      new mapboxgl.NavigationControl({
        visualizePitch: true,
      }),
    );
    // 添加比例尺
    const scale = new mapboxgl.ScaleControl({
      maxWidth: 120,
    });
    scene.map.addControl(scale);
    scale.setUnit('metric');

    // 添加全局缩放
    scene.map.addControl(new mapboxgl.FullscreenControl());

    // 添加定位控件
    scene.map.addControl(
      new mapboxgl.GeolocateControl({
        positionOptions: {
          enableHighAccuracy: true,
        },
        trackUserLocation: true,
      }),
    );
    scene.map.on('load', () => {
      resolve(true);
    });
  });
};
const closePreviewDialog = () => {
  emits('closePreviewDialog');
};
const getImageCoodinates = (source: any) => {
  return [
    [source.bbox[0], source.bbox[3]],
    [source.bbox[2], source.bbox[3]],
    [source.bbox[2], source.bbox[1]],
    [source.bbox[0], source.bbox[1]],
  ];
};
const previewDataInMap = () => {
  return new Promise((resolve) => {
    const source = preview.data;
    const sourceId = `preview_source_${source.id}`;
    let sourceOptions = null;
    const sourceType = preview.data.type;
    if (sourceType === 'image') {
      sourceOptions = {
        type: 'image',
        url: source.url,
        coordinates: getImageCoodinates(source),
      };
    } else if (sourceType === 'tiles') {
      sourceOptions = {
        type: 'raster',
        tiles: [source.url],
        tileSize: 256,
      };
    }
    scene.map.addSource(sourceId, sourceOptions);
    const layerOption = {
      id: `preview_layer_${preview.data.id}`,
      name: preview.data.name,
      type: 'raster',
      layout: {
        visibility: 'visible',
      },
      source: sourceId,
    } as any;
    scene.map.addLayer(layerOption);
    scene.map.fitBounds(preview.data.bbox, {
      padding: { top: 10, bottom: 25, left: 15, right: 5 },
    });
    resolve('资源加载完毕');
  });
};
onMounted(() => {
  nextTick(async () => {
    await initMap();
    preview.data = currentRasterData as any;
    typeOfRaster.value =
      preview.data.oriFileId === null
        ? preview.data.url.split('.').pop()!
        : 'tiff';
    isloading.value = false;
    bboxTop.value = preview.data.bbox[3];
    bboxBottom.value = preview.data.bbox[1];
    bboxLeft.value = preview.data.bbox[0];
    bboxRight.value = preview.data.bbox[2];
    if (typeOfRaster.value === 'tiff') getBandCount();
    await previewDataInMap();
  });
});
</script>

<template>
  <div>
    <ElDialog
      v-model="isDialogShow"
      align-center
      @close="closePreviewDialog"
      destroy-on-close
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h2 :id="titleId" :class="titleClass" style="font-size: 20px">
            栅格服务资源预览
          </h2>
        </div>
      </template>
      <ElDivider style="margin-top: 0; margin-bottom: 10px" />
      <ElRow class="all">
        <ElCol :span="12">
          <ElRow style="width: 100%; height: 100%; padding-bottom: 10px">
            <div id="map"></div>
          </ElRow>
        </ElCol>
        <ElDivider direction="vertical" />
        <ElCol :span="12">
          <div class="rightCon">
            <ElScrollbar style="max-height: 90%; padding: 5px">
              <ElDescriptions
                style="width: 100%; max-height: 90%"
                v-loading="isloading"
                element-loading-text="正在加载数据信息..."
                title="数据信息(ReadOnly)"
                size="large"
                :column="1"
                border
              >
                <ElDescriptionsItem
                  width="200px"
                  style="width: 100%"
                  align="center"
                >
                  <template #label>
                    <div class="cell-item">数据名称</div>
                  </template>
                  {{ preview.data.name }}
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">类型</div>
                  </template>
                  {{ preview.data.type }}
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">数据类型</div>
                  </template>
                  {{ typeOfRaster }}
                </ElDescriptionsItem>
                <ElDescriptionsItem
                  align="center"
                  v-if="typeOfRaster === 'tiff'"
                >
                  <template #label>
                    <div class="cell-item">波段数量</div>
                  </template>
                  {{ bandCount }}
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">空间范围</div>
                  </template>
                  Top:
                  {{ bboxTop }}<br />
                  Left:
                  {{ bboxLeft }}&nbsp;&nbsp; Right: {{ bboxRight }}<br />
                  Bottom:
                  {{ bboxBottom }}
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">发布者</div>
                  </template>
                  {{ publisher }}
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">数据拥有者</div>
                  </template>
                  {{ preview.data.ownerCount }}
                </ElDescriptionsItem>
              </ElDescriptions>
            </ElScrollbar>
          </div>
        </ElCol>
      </ElRow>
    </ElDialog>
  </div>
</template>

<style scoped>
#map {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  border: 1 px solid black;
  border-radius: 10px;
}

.all {
  box-sizing: border-box;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  width: auto;
  height: 50vh;
  padding-top: 5px;
  border: 1 px solid;
}

.cell-item {
  display: inline-block;
  width: 70px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-dialog) {
  width: 60vw;

  /* height: 80vh; */
  border-radius: 20px;
}

.rightCon {
  width: 98%;
  height: 100%;
  padding: 10px;

  /* background-color: aqua; */
}

.el-tab-paneCon {
  width: 100%;
  height: 100%;
}

.my-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 20px;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-left: 20px;
  font-size: 30px;
}

:deep(.el-dialog__body) {
  padding-top: 5px;
  padding-bottom: 0;
}

:deep(.el-dialog__footer) {
  padding: 5px;
}

.titleClass {
  font-size: 30px;
}

:deep(.el-descriptions) {
  width: 100%;
}

.el-divider--vertical {
  height: 100%;
  margin-left: 10px;
}

.el-descriptions {
  max-height: 40vh;
}

.tableCon {
  width: 100%;
  height: 64vh;
}

/* 隐藏logo */
:deep(.mapboxgl-ctrl-logo) {
  display: none !important;
}

:deep(.mapboxgl-ctrl-bottom-right) {
  display: none !important;
}
</style>
